<template>
  <div class="app-container order-class">
    <el-row style="margin-bottom:10px">
      <el-col :span="3">
        <el-input v-model="search.keyword" placeholder="Keyword" style="width:95%" />
      </el-col>
      <el-col :span="3">
        <el-select v-model="search.hotel_id" clearable placeholder="Please Choose Hotel" style="width:95%" no-data-text="Can't find record">
          <el-option
            v-for="item in hotellist"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-col>
      <el-col :span="3">
        <el-date-picker
          v-model="search.time_start"
          style="width:95%"
          type="date"
          placeholder="Start Time"
        />
      </el-col>
      <el-col :span="3">
        <el-date-picker
          v-model="search.time_end"
          style="width:95%"
          type="date"
          placeholder="End Time"
        />
      </el-col>
      <el-col :span="3">
        <el-select v-model="search.status" clearable placeholder="Please Choose Status" style="width:95%" no-data-text="Can't find record">
          <el-option
            v-for="item in statuslist"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-col>
      <el-button type="primary" icon="el-icon-search" @click="gettableinto" />
      <el-button v-show="createShow" type="primary" @click="handleAddRole">Add</el-button>
      <el-input v-model.number="total_row_num" placeholder="Quantity" style="width: 100px" @oninput="value=value.replace(/^\d+$|^\d+[.]?\d+$/,'')" />
      <el-button type="primary" icon="el-icon-download" circle @click="selectPage" />
      <el-popover
        v-model="emailVisible"
        placement="top"
        width="400"
      >
        <el-form ref="emailForm" :model="emailModel" :rules="emailRules" label-width="60px" label-position="left">
          <el-form-item v-for="(email, index) in emailModel.emails" :key="index" label="Email" prop="email">
            <el-row>
              <el-col :span="20">
                <el-input v-model="emailModel.emails[index]" placeholder="Email" />
              </el-col>
              <el-col :span="4" style="padding-left:20px">
                <el-link icon="el-icon-delete" @click="delEmail(index)" />
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <el-button type="primary" size="mini" @click="addEmail">add</el-button>
        <div style="text-align: right; margin: 0">
          <el-button size="mini" type="text" @click="emailVisible = false">cancel</el-button>
          <el-button type="primary" size="mini" @click="sendEmail">send</el-button>
        </div>
        <el-button slot="reference" type="primary" icon="el-icon-message" circle />
      </el-popover>
      <!-- <el-link icon="el-icon-download" href="http://work.dcloud.yunku.live/api/user/order/index?download=1.html" type="primary">Download</el-link> -->
    </el-row>
    <el-table
      :data="rolesList"
      style="width: 100%;margin-top:30px;"
      :cell-style="cellChangeColor"
      :empty-text="empty_text"
      border
    >
      <!--      columnIndex 0-->
      <el-table-column align="center" prop="id" label="ID" width="50">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>

      <!--      columnIndex 1-->
      <el-table-column align="header-center" label="Title" width="150">
        <template slot-scope="scope">{{ scope.row.title }}</template>
      </el-table-column>

      <!--      columnIndex 2 -->
      <el-table-column align="header-center" label="Created By" width="150">
        <template slot-scope="scope">{{ scope.row.user_name }}</template>
      </el-table-column>

      <!--      columnIndex 3-->
      <el-table-column align="header-center" label="Assigned To">
        <template slot-scope="scope">{{ scope.row.staff_names }}</template>
      </el-table-column>

      <!--      columnIndex 4-->
      <el-table-column align="header-center" label="Room & Location">
        <template slot-scope="scope">{{ scope.row.desc }}</template>
      </el-table-column>

      <!--      columnIndex 5-->
      <el-table-column align="header-center" label="Client/Site">
        <template slot-scope="scope">{{ scope.row.hotel_name }}</template>
      </el-table-column>

      <!--      columnIndex 6-->
      <el-table-column align="header-center" label="Work Instruction">
        <template slot-scope="scope">
          <span v-if="scope.row.work_type=='1'">{{ scope.row.wi_names.replace(/\,/g, '\n') }}</span>
          <span v-if="scope.row.work_type=='2'">{{ scope.row.ad_hoc_work.replace(/\,/g, '\n') }}</span>
        </template>
      </el-table-column>

      <!--      columnIndex 7-->
      <el-table-column align="header-center" label="Start Date">
        <template slot-scope="scope">{{ scope.row.start_date }}</template>
      </el-table-column>

      <!--      columnIndex 8-->
      <el-table-column align="header-center" label="Due Date" width="180">
        <template slot-scope="scope">{{ scope.row.due_date }}</template>
      </el-table-column>

      <!--      columnIndex 9-->
      <el-table-column align="header-center" label="Status" width="110">
        <template slot-scope="scope">{{ scope.row.status_name }}</template>
      </el-table-column>

      <!--      columnIndex 10-->
      <el-table-column align="header-center" label="Feedback" width="110">
        <template slot-scope="scope">{{ scope.row.order_sign }}</template>
      </el-table-column>

      <!--      columnIndex 11-->
      <el-table-column align="center" label="Action" width="100">
        <template slot-scope="scope">
          <!-- <el-row>
            <el-col :span="8">
              <el-link v-show="editShow" class="el-icon-edit icon-class" @click="handleEdit(scope)" />
            </el-col>
            <el-col :span="8">
              <el-link class="el-icon-document icon-class" @click="openorderdetailsComp(scope)" />
            </el-col>
            <el-col :span="8">
              <el-link v-show="editShow" class="el-icon-delete icon-class" @click="handleDelete(scope)" />
            </el-col>
          </el-row> -->
          <el-row>
            <el-col>
              <el-link v-show="editShow" @click="handleEdit(scope)">Edit</el-link>
              <br>
              <el-link @click="openorderdetailsComp(scope)">Details</el-link>
              <br>
              <el-link v-show="editShow" @click="handleDelete(scope)">Delete</el-link>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? 'Edit Work Order' : 'New Work Order'"
    >
      <div style="margin:0 30px">
        <el-form ref="connectForm" :model="orderinfo" :rules="rules" label-width="150px" label-position="left">
          <el-form-item label="Title" prop="title">
            <el-input v-model="orderinfo.title" placeholder="Title" />
          </el-form-item>
          <el-form-item label="Room & Others" prop="desc">
            <el-input v-model="orderinfo.desc" placeholder="Handyfix user's address" />
          </el-form-item>
          <el-form-item label="Priority" prop="priority">
            <el-select v-model="orderinfo.priority" placeholder="Please Choose" no-data-text="Can't find record">
              <el-option
                v-for="item in prioritylist"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="Client" prop="hotel_id">
            <el-select v-model="orderinfo.hotel_id" placeholder="Handyfix username (Contact No)" no-data-text="Can't find record" @change="gethotelcontectinfo">
              <el-option
                v-for="item in hotellist"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="Client Contact" prop="hotecontectlids">
            <el-select v-model="hotecontectlids" style="width:100%" placeholder="Please Choose" no-data-text="Can't find record">
              <el-option
                v-for="item in hotecontectllist"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="Work Instructions" prop="wiids">
            <el-select v-model="wiids" style="width:100%" multiple placeholder="Please Choose" no-data-text="Can't find record">
              <el-option
                v-for="item in wilist"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="Staffs" prop="staffsids">
            <el-select v-model="staffsids" style="width:100%" multiple placeholder="Please Choose" no-data-text="Can't find record">
              <el-option
                v-for="item in staffslist"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="Due date">
            <el-date-picker v-model="orderinfo.due_date" type="datetime" placeholder="End Date" />
          </el-form-item>
          <el-form-item v-if="notesText.length > 0" label="Note">
            <el-input v-model="notesText" type="textarea" :autosize="{ minRows: 2 }" placeholder="Note" disabled />
          </el-form-item>
          <el-form-item v-for="(note, index) in orderinfo.notes" :key="index" label="Note">
            <el-input v-model="orderinfo.notes[index]" placeholder="Note" />
          </el-form-item>
        </el-form>
        <!-- <section>
          <my-test
            v-for="(item, index) in notes"
            :key="index"
            :index="index"
            :item-c="item"
          />
        </section> -->
        <el-button size="mini" icon="el-icon-circle-plus" @click="add" />
        <div style="text-align:right;">
          <el-button type="danger" @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="confirm">Confirm</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogVisible_per"
      title="Download"
      width="500px"
    >
      <div>
        <el-row style="margin-bottom:20px;margin-top: -10px;padding-left: 20px">
          <el-col v-for="item in total_row_total" :key="item" :span="6" style="margin-bottom:10px">
            <el-link type="primary" @click="downloadWorkOrder(item)">Page {{ item }}</el-link>
          </el-col>
        </el-row>
      </div>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible_per = false">Cancel</el-button>
      </div>
    </el-dialog>

    <el-pagination
      style="margin-top:10px;float:right"
      background
      layout="slot,prev,pager,next"
      :total="totalpage"
      :current-page="search.page"
      :page-size="search.per_page"
      @current-change="handleIndexChange"
    >
      <span class="el-pagination__total">Total {{ totalpage }}</span>
    </el-pagination>
  </div>
</template>

<script>
import { baseAPI } from '@/utils/request'
// import MyTest from './noets.vue'
import {
  getorderinfo,
  getdictionary,
  saveorder,
  deleteorder,
  getdetails
} from '@/api/order/index'
import { parseTime } from '@/utils'
import { getToken } from '@/utils/auth' // get token from cookie
import { Loading } from 'element-ui'

const defaultOrderInfo = {
  id: '',
  title: '',
  desc: '',
  priority: '',
  hotel_id: '',
  hotel_contact_ids: [],
  wi_ids: [],
  notes: [],
  staffs: [],
  due_date: ''
}

export default {
  components: {
    // MyTest
  },
  data() {
    return {
      total_row_num: 50,
      total_row_total: undefined,
      createShow: false,
      editShow: false,
      emailVisible: false,
      dialogVisible_per: false,
      emailModel: {
        emails: ['']
      },
      statuslist: [],
      orderinfo: {
        id: '',
        title: '',
        desc: '',
        priority: 2,
        hotel_id: '',
        hotel_contact_ids: [],
        wi_ids: [],
        notes: [],
        staffs: [],
        due_date: ''
      },
      search: {
        time_start: '',
        time_end: '',
        hotel_id: '',
        keyword: '',
        page: 1,
        request_type: '',
        status: '',
        per_page: 10,
        search_type: ''
      },
      notesText: '',
      notes: [{
        note: ''
      }],
      empty_text: '',
      prioritylist: [],
      hotellist: [],
      hotecontectllist: [],
      hotecontectlids: '',
      wilist: [],
      wiids: [],
      staffslist: [],
      staffsids: [],
      totalpage: 0,
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      tokenData: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      emailRules: {
        email: [
          { type: 'email', message: 'Please enter the correct email format', trigger: 'blur' }]
      },
      rules: {
        title: [{ required: true, message: 'Please enter a title', trigger: 'blur'
        }],
        desc: [{ required: true, message: 'Please Enter Room & Others', trigger: 'blur'
        }],
        priority: [{ required: true, message: 'Please Choose Priority', trigger: 'change'
        }],
        hotel_id: [{ required: true, message: 'Please Choose Hotel', trigger: 'change'
        }]
      }
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  watch: {
    dialogVisible(newValue, oldValue) {
      this.orderinfo = Object.assign({}, defaultOrderInfo)
      if (this.$refs['connectForm']) this.$refs['connectForm'].clearValidate()

      if (!newValue) {
        this.notesText = ''
      } else {
        this.orderinfo.notes = []
        this.orderinfo.notes.push('')
      }
    },
    emailVisible(newValue, oldValue) {
      if (this.$refs['emailForm']) this.$refs['emailForm'].clearValidate()
      if (!newValue) {
        this.emailModel.emails = ['']
      }
    }
  },
  created() {
    // Mock: get all routes and roles list from server
    this.getRoutes()
    this.getRoles()
    this.conRouter()
    this.conToken()

    this.search.search_type = this.$route.path === '/order/index' ? '' : this.$route.path
  },
  methods: {
    addEmail() {
      this.emailModel.emails.push('')
    },
    delEmail(val) {
      this.emailModel.emails.splice(val, 1)
    },
    add() {
      this.orderinfo.notes.push('')
      // this.notes.push({
      //   note: ''
      // })
    },
    cellChangeColor({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 9) {
        if (row.overdue) { return { backgroundColor: '#f74969', color: 'white' } }
        if (row.upcoming) { return { backgroundColor: '#095bd4', color: 'white' } }
        if (row.status === 2) { return { backgroundColor: '#9267be', color: 'white' } }
        if (row.status === 3) { return { backgroundColor: '#6ed3d0', color: 'white' } }
      }
      if (row.overdue && columnIndex === 8) { return { backgroundColor: '#f74969', color: 'white' } }
      return ''
    },
    status_change(scope) {
      if (scope.row.status === 1) {
        return 'table-info-row1'
      } else if (scope.row.status === 2) {
        return 'table-info-row2'
      } else if (scope.row.status === 3) {
        return 'table-info-row3'
      }
    },
    handleIndexChange(index) {
      this.search.page = index
      this.getRoles()
    },
    handleToOrder(scope) {
      this.$router.push({
        path: '/handyFix/index',
        query: { order_no: scope.row.user_order_no }
      })
    },
    async getRoutes() {
      const res = await baseAPI.get('user/role/routes')
      this.serviceRoutes = res
      this.routes = res
    },
    async conRouter() {
      const { roles, role_infos } = await this.$store.dispatch('user/getInfo')
      if (roles.some(p => p === '1')) {
        this.createShow = true
        this.editShow = true
      } else {
        const res = role_infos[0].routes
        this.createShow = res.some(p => p === '/order/add')
        this.editShow = res.some(p => p === '/order/edit')
      }
    },
    async conToken() {
      this.tokenData = getToken()
    },
    gettableinto() {
      this.keyword = this.keywords
      this.getRoles()
    },
    async getRoles() {
      this.empty_text = 'Loading ......'
      await getorderinfo(this.search).then(response => {
        this.rolesList = response.data
        this.totalpage = response.total
        this.per_page = response.per_page
        this.current_page = response.current_page
        this.empty_text = 'Can\'t find record in table'
      }).catch(() => {
        this.rolesList = []
        this.empty_text = 'Can\'t find record in table'
      })
      await this.gethotelinfo()
    },
    async getpriorityinfo() {
      this.prioritylist = await getdictionary({ dict_type: 'priority' })
      this.orderinfo.priority = 2
    },
    async gethotelinfo() {
      this.hotellist = await getdictionary({ dict_type: 'hotel' })
      this.statuslist = await getdictionary({ dict_type: 'order_status' })
    },
    async gethotelcontectinfo(val) {
      this.hotecontectllist = await getdictionary({ dict_type: 'hotel_contact', hotel_id: val })
      this.hotecontectlids = ''
      this.wiids = []
      this.getwiinfo(val)
    },
    async getwiinfo(val) {
      this.wilist = await getdictionary({ dict_type: 'wi', hotel_id: val })
    },
    async getstaffsinfo(val) {
      this.staffslist = await getdictionary({ dict_type: 'staff' })
    },
    handleAddRole() {
      this.notes.splice(this.notes)
      this.notes.push({ note: '' })
      this.hotecontectlids = ''
      this.wiids = []
      this.staffsids = []
      // this.orderinfo.notes.push('')
      this.getpriorityinfo()
      this.gethotelinfo()
      this.getstaffsinfo()
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    async handleEdit(scope) {
      this.notes.splice(this.notes)
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.getpriorityinfo()
      this.gethotelinfo()
      this.getstaffsinfo()
      const res = await getdetails({ id: scope.row.id })
      await this.gethotelcontectinfo(res.hotel_id)
      this.orderinfo.id = res.id
      this.orderinfo.title = res.title
      this.orderinfo.desc = res.desc
      this.orderinfo.priority = res.priority
      this.orderinfo.hotel_id = res.hotel_id
      this.orderinfo.due_date = new Date(res.due_date.replace('-', '').replace('PM', '').replace('AM', ''))
      this.hotecontectlids = res.hotel_contact && res.hotel_contact.length > 0 ? res.hotel_contact[0].id : ''
      // this.hotecontectlids = res.hotel_contact.map(function(v) { return v.id })
      this.wiids = res.wi.map(function(v) { return v.wi_id })
      this.staffsids = res.staffs.map(function(v) { return v.id })
      for (var i = 0; i < res.notes.length; i++) {
        this.notes.push({ note: res.notes[i].note })
      }
      this.notesText = res.notes.map(element => element.user_name + ': ' + element.note).join('\r\n')
    },
    handleDelete({ $index, row }) {
      this.$confirm('Confirm to remove the Work Order?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      })
        .then(async() => {
          await deleteorder({ id: row.id })
          // baseAPI.get('user/witemplate/delete?id=' + row.id + '')
          this.rolesList.splice($index, 1)
          this.getRoles()
          this.$message({
            type: 'success',
            message: 'Delete succed!'
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    openorderdetailsComp(scope) {
      this.$router.push({
        path: '/order/orderdetails',
        query: { id: scope.row.id }
      })
    },
    async confirm() {
      this.$refs.connectForm.validate(async valid => {
        if (valid) {
          if (this.orderinfo.due_date) {
            this.orderinfo.due_date = parseTime(this.orderinfo.due_date, '{y}-{m}-{d}  {h}:{i}:{s}')
          }
          this.orderinfo.hotel_contact_ids = []
          this.orderinfo.hotel_contact_ids.push(this.hotecontectlids)
          this.orderinfo.wi_ids = this.wiids
          this.orderinfo.staffs = this.staffsids
          this.orderinfo.notes = this.orderinfo.notes.filter(note => note && note.trim())
          // this.orderinfo.notes = this.notes
          // this.orderinfo.notes = this.notes.map(function(v) { return v.note })
          // console.log(this.orderinfo)
          await saveorder(this.orderinfo)
          this.dialogVisible = false
          await this.getRoles()
        }
      })
    },
    async selectPage() {
      if (!this.total_row_num || this.total_row_num <= 0) {
        this.$message({
          type: 'warning',
          message: 'Please enter the quantity per page!'
        })
        return
      } else {
        const per_search = Object.assign({}, this.search)
        per_search.request_type = 'download_query'

        await getorderinfo(per_search).then(async response => {
          if (response.total > 0) {
            if (response.total <= this.total_row_num) {
              // 直接下载
              return this.downloadWorkOrder(1)
            }
            this.total_row_total = Math.ceil(response.total / this.total_row_num)
            this.dialogVisible_per = true
          } else {
            this.$message({
              type: 'warning',
              message: 'Can\'t find record to download!'
            })
          }
        })
      }
    },
    async downloadWorkOrder(value) {
      this.downloadSearch = Object.assign({}, this.search)
      this.downloadSearch.download = 1
      if (this.downloadSearch.time_start) {
        this.downloadSearch.time_start = parseTime(this.downloadSearch.time_start, '{y}-{m}-{d}')
      }
      if (this.downloadSearch.time_end) {
        this.downloadSearch.time_end = parseTime(this.downloadSearch.time_end, '{y}-{m}-{d}')
      }
      const url = 'user/order/index?keyword=' + this.downloadSearch.keyword + '&page=' + value + '&per_page=' + this.total_row_num + '&hotel_id=' + this.downloadSearch.hotel_id +
      '&time_start=' + this.downloadSearch.time_start + '&time_end=' + this.downloadSearch.time_end + '&request_type=download&token=' + this.tokenData

      window.open(process.env.VUE_APP_BASE_API + url)
    },
    async sendEmail() {
      this.loadingInstance = Loading.service({})
      this.$refs.emailForm.validate(async valid => {
        if (valid) {
          this.downloadSearch = Object.assign({}, this.search)
          this.downloadSearch.download = 1
          if (this.downloadSearch.time_start) {
            this.downloadSearch.time_start = parseTime(this.downloadSearch.time_start, '{y}-{m}-{d}')
          }
          if (this.downloadSearch.time_end) {
            this.downloadSearch.time_end = parseTime(this.downloadSearch.time_end, '{y}-{m}-{d}')
          }
          const requestEmail = this.emailModel.emails.join(',')
          const url = 'user/order/index?keyword=' + this.downloadSearch.keyword + '&page=' + this.downloadSearch.page + '&hotel_id=' + this.downloadSearch.hotel_id +
          '&time_start=' + this.downloadSearch.time_start + '&time_end=' + this.downloadSearch.time_end + '&request_type=send_email&emails=' + requestEmail
          await baseAPI.get(url, { timeout: 0 })
          this.emailVisible = false
          this.$message({
            type: 'success',
            message: 'Email sent successfully!'
          })
        }
        this.loadingInstance.close()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
  .icon-class {
    font-size: 20px;
  }
}
</style>

<style>
.table-info-row1 td {
      color: #03be1cef;
 }
.table-info-row2 td {
      color: #0057facb;
 }
.table-info-row3 td {
      color: #fd0000c5;
 }
.order-class .el-table .cell {
  white-space: pre-line !important;
}
</style>
